class WebSocketClient {
    constructor() {
        this.ws = null;
        this.connected = false;
        this.retryCount = 0;
        this.maxRetries = 5;
        this.retryDelay = 3000;
        this.statusLight = document.querySelector('.status-light');
        this.init();
    }

    init() {
        this.updateStatusLight();
        this.connect();
        
        // 绑定文件刷新按钮
        document.getElementById('refresh-files')?.addEventListener('click', () => {
            this.getServerFiles();
        });
    }

    connect() {
        this.ws = new WebSocket('ws://127.0.0.1:8766');

        this.ws.onopen = () => {
            console.log('WebSocket connected');
            this.connected = true;
            this.retryCount = 0;
            this.updateStatusLight();
            this.getServerFiles();
        };

        this.ws.onmessage = (event) => this.handleMessage(event);
        this.ws.onerror = (error) => this.handleError(error);
        this.ws.onclose = () => this.handleClose();
    }

    handleMessage(event) {
        try {
            const data = JSON.parse(event.data);
            console.log('Received:', data);

            if (data.type === 'server_files') {
                this.updateServerFiles(data.files);
            }
            if (data.type === 'delete_file_result') {
                this.handleDeleteResult(data.success, data.message);
            }
            if (data.type === 'upload_progress') {
                this.updateUploadProgress(data.progress);
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
    }

    getServerFiles() {
        if (this.connected) {
            this.sendMessage('get_server_files');
        }
    }

    deleteServerFile(filePath) {
        if (this.connected) {
            this.sendMessage('delete_file', { file_path: filePath });
        }
    }


    updateServerFiles(files) {
        const fileListContainer = document.getElementById('file-list-container');
        if (!fileListContainer) return;

        fileListContainer.innerHTML = '';

        const table = document.createElement('table');
        table.className = 'file-table';

        // 创建表头
        const headerRow = document.createElement('tr');
        ['文件名', 'Hash', '大小', '修改时间', '操作'].forEach(text => {
            const th = document.createElement('th');
            th.textContent = text;
            headerRow.appendChild(th);
        });
        table.appendChild(headerRow);

        // 创建文件行
        files.forEach(file => {
            const row = document.createElement('tr');
            
            // 文件名
            const nameCell = document.createElement('td');
            nameCell.textContent = file.name;
            row.appendChild(nameCell);

            // 文件哈希值
            const hashCell = document.createElement('td');
            hashCell.textContent = file.hash;
            row.appendChild(hashCell);

            // 文件大小
            const sizeCell = document.createElement('td');
            sizeCell.textContent = file.size;
            row.appendChild(sizeCell);

            // 修改时间
            const timeCell = document.createElement('td');
            timeCell.textContent = file.modified;
            row.appendChild(timeCell);

            // 操作
            const actionCell = document.createElement('td');
            const deleteButton = document.createElement('button');
            deleteButton.className = 'delete-btn';
            deleteButton.innerHTML = '<i class="fa-solid fa-trash"></i> 删除';
            deleteButton.addEventListener('click', () => {
                if (confirm(`确定要删除 ${file.name} 吗？`)) {
                    this.deleteServerFile(file.path);
                }
            });
            actionCell.appendChild(deleteButton);
            row.appendChild(actionCell);

            table.appendChild(row);
        });

        fileListContainer.appendChild(table);
    }

    handleDeleteResult(success, message) {
        if (success) {
            alert('文件删除成功');
            this.getServerFiles();
        } else {
            alert(`文件删除失败：${message}`);
        }
    }

    sendMessage(type, data = {}) {
        if (!this.connected) {
            console.error('Cannot send message - WebSocket not connected');
            return;
        }
        const message = { type, ...data };
        this.ws.send(JSON.stringify(message));
    }

    updateStatusLight() {
        this.statusLight.classList.remove('connected', 'disconnected', 'connecting');
        if (this.connected) {
            this.statusLight.classList.add('connected');
        } else if (this.retryCount > 0 && this.retryCount < this.maxRetries) {
            this.statusLight.classList.add('connecting');
        } else {
            this.statusLight.classList.add('disconnected');
        }
    }

    handleError(error) {
        console.error('WebSocket error:', error);
        this.updateStatusLight();
    }

    handleClose() {
        console.log('WebSocket disconnected');
        this.connected = false;
        this.updateStatusLight();
        if (this.retryCount < this.maxRetries) {
            this.retryCount++;
            console.log(`Reconnecting in ${this.retryDelay / 1000} seconds...`);
            setTimeout(() => {
                this.connect();
                this.updateStatusLight();
            }, this.retryDelay);
        } else {
            this.updateStatusLight();
        }
    }
}

// 初始化 WebSocket 客户端
const wsClient = new WebSocketClient();

// 页面加载时获取文件列表
document.addEventListener('DOMContentLoaded', () => {
    wsClient.getServerFiles();
});